using System;
using System.Data;

namespace PArticulo
{


	public class ArticuloPersister
	{

		public ArticuloPersister ()
		{
		}
		
		private const string insertCommand = "insert into articulo (nombre, precio, categoria) values (?nombre, ?precio, ?categoria)";
		private const string updateCommand = "update articulo set nombre=?nombre, precio=?precio, categoria=?categoria where id=?id";
		private const string selectCommand = "select * from articulo where id=?id";
		
		public void Save (object model)
		{
			Save((Articulo).model);
		}
		
		public void Save (Articulo articulo)
		{			
			IDbCommand dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
			
			if(articulo.Id == 0) //insert
				dbCommand.CommandText = insertCommand;
			else { //update
				dbCommand.CommandText = updateCommand;
				addParameter(dbCommand, "id", articulo.Id);
			}
			
			addParameter(dbCommand, "nombre", articulo.Nombre);
			addParameter(dbCommand, "precio", articulo.Precio);
			addParameter(dbCommand, "categoria", articulo.Categoria);
			
			dbCommand.ExecuteNonQuery();
		}
		
		private void addParameter(IDbCommand dbCommand, string parameterName, object parameterValue)
		{
			IDbDataParameter dbDataParameter = dbCommand.CreateParameter();
			dbDataParameter.ParameterName = parameterName;
			dbDataParameter.Value = parameterValue;
			dbCommand.Parameters.Add(dbDataParameter);
		}
		
		public object Load (Type type, object id)
		{
			
			IDbCommand dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
			dbCommand.CommandText = selectCommand;
			addParameter(dbCommand, "id", id);
			
			IDataReader dataReader = dbCommand.ExecuteReader();
			dataReader.Read(); //leemos el primer registro (y único)
			
			
			
			Articulo articulo = new Articulo();
			articulo.Id = (long)id;
			articulo.Nombre = (string)dataReader["nombre"];
			articulo.Precio = (decimal)dataReader["precio"];
			articulo.Categoria = dataReader["categoria"] is DBNull ? (long?)null : (long)dataReader["categoria"];
			
			dataReader.Close();
			
			return articulo;
		}
	}
}
